#include "mmap_file_op.h"

#include <iostream>

using namespace std;
using namespace project;

const static largefile::MMapOption mmap_option = {10240000, 4096, 4096};

int main(void)
{
    int ret = 0;
    const char *filename = "mmap_file_op.txt";
    largefile::MMapFileOperation *mmfo = new largefile::MMapFileOperation(filename);

    // 测试打开文件
    int fd = mmfo->open_file();
    if (fd < 0)
    {
        fprintf(stderr, "open file %s failed.reason:%s\n", filename, strerror(-fd));
        exit(-1);
    }

    // 测试文件映射到内存
    ret = mmfo->mmap_file(mmap_option);
    if (ret == largefile::TFS_ERROR)
    {
        fprintf(stderr, "mmap_file failed. reason:%s\n", strerror(errno));
        mmfo->close_file();
        exit(-2);
    }

    // 测试读和写文件
    char buffer[128 + 1];
    memset(buffer, '6', 128);
    buffer[127] = '\n';

    ret = mmfo->pwrite_file(buffer, 128, 8);
    if (ret < 0)
    {
        if (ret == largefile::EXIT_DISK_OPER_INCOMPLETE)
        {
            fprintf(stderr, "read or write length is less than required");
        }
        else
        {
            fprintf(stderr, "pwrite file %s failed.reason:%s\n", filename, strerror(-ret));
        }
    }

    memset(buffer, 0, 128);
    ret = mmfo->pread_file(buffer, 128, 8);
    if (ret < 0)
    {
        if (ret == largefile::EXIT_DISK_OPER_INCOMPLETE)
        {
            fprintf(stderr, "read or write length is less than required");
        }
        else
        {
            fprintf(stderr, "pread file %s failed.reason:%s\n", filename, strerror(-ret));
        }
    }
    else
    {
        buffer[128] = '\0';
        printf("read:%s\n", buffer);
    }

    // 测试内存文件写回到磁盘
    ret = mmfo->flush_file();
    if (ret == largefile::TFS_ERROR)
    {
        fprintf(stderr, "flush file failed. reason:%s\n", strerror(errno));
    }

    // 测试写文件的超出内存大小，需要扩容的情况
    memset(buffer, '8', 128);
    buffer[127] = '\n';
    ret = mmfo->pwrite_file(buffer, 128, 4000);

    mmfo->munmap_file();

    mmfo->close_file();

    return 0;
}